<template>
  <van-dialog v-model:show="isShow" class="custom-dialog">
    <van-form ref="formRef" @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="formData.phone"
          name="phone"
          label=""
          placeholder="请输入您的手机号"
          clearable
          :rules="[{ required: true, message: '请输入您的手机号' }]"
        >
          <template #left-icon>
            <div class="phone-icon-image">
              <van-image :src="phoneIcon" width="22" height="22"></van-image>
            </div>
          </template>
        </van-field>
        <van-field
          v-model="formData.kaptcha"
          name="kaptcha"
          label=""
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
          clearable
        >
          <template #left-icon>
            <div class="phone-icon-image">
              <van-image :src="codeIcon" width="22" height="22"></van-image>
            </div>
          </template>
          <template #button>
            <div class="code-img">
              <van-image :src="codeImg" @click="refreshCode"></van-image>
            </div>
          </template>
        </van-field>
        <div class="tip">点击图片刷新</div>
      </van-cell-group>
    </van-form>
    <template #title>
      <div class="custom-dialog-header">
        <span v-if="title">{{ title }}</span>
        <van-icon name="cross" class="close-icon" @click="onClose" />
      </div>
    </template>
    <template #footer>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          color="#e6232b"
          native-type="submit"
          :loading="loading"
          @click="onSubmit"
          >下一步</van-button
        >
      </div>
    </template>
  </van-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { downloadApk, refreshCodeImg, countPv } from "@/api/channel";
import { mockApi, detectDevice } from "@/utils/util";
import { useRouter } from "vue-router";
import phoneIcon from "@/assets/channel/phone-icon.png";
import codeIcon from "@/assets/channel/code-icon.png";
import { showToast } from "vant";

const router = useRouter();

const codeImg = ref("data:image/png;base64,");

const title = ref("");
const loading = ref(false);
const channel = ref("");
const deviceType = ref<string>(detectDevice());
// const {channel} =
// const props = defineProps({
//   phone: String,
//   channel: String,
// });
const isShow = ref(false);
const formData = reactive({
  phone: "",
  channelCode: "",
  channelType: 0,
  kaptcha: "",
});
const arrayBufferToBase64 = (buffer) => {
  let binary = "";
  let bytes = new Uint8Array(buffer);
  let len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return "data:image/jpeg;base64," + window.btoa(binary);
};

onMounted(() => {
  // let deviceType = detectDevice();
  console.log("submit dialog device", deviceType.value);
  // await refreshCode();
});

const refreshCode = async () => {
  const res: any = await refreshCodeImg();
  // console.log("res: ", res);
  codeImg.value = arrayBufferToBase64(res);
};

const onSubmit = async (values: any) => {
  // console.log("登录submit", values);
  try {
    console.log("onsubmit: ", formData);
    if (!formData.kaptcha) {
      showToast("请填写验证码！");
      return;
    }
    if (!formData.phone) {
      showToast("请填写手机号！");
      return;
    }
    loading.value = true;
    //   const [err] = await usePromise(userStore.login(params));
    const res = await downloadApk(formData);
    console.log(res);
    console.log("success: ", 200 == res.code);
    if (200 == res.code) {
      console.log("提交成功deviceType: ", deviceType.value);
      // showToast(deviceType.value);
      if (deviceType.value == "Android") {
        router.push("/guideAndroid");
      } else if (deviceType.value == "IOS") {
        router.push("/guideIos");
      }

      //
      // if (deviceType.value == "Android") {
      //   let downLoadUrl =
      //     "https://dch5.dev.qbclub.club/download/app/youpin.apk";
      //   window.location.href = downLoadUrl;
      // } else if (deviceType.value == "IOS") {
      //   router.push("/guideIos");
      // } else {
      // }
      //
    } else {
      console.log(res);
      // showToast("验证码错误！");
    }
  } catch {
  } finally {
    loading.value = false;
  }

  //   if (err) return;
  //   const redirect = route.query.redirect ?? "/";
  //   router.replace(redirect as string);
};

const open = async (phone: string, channelCode: string) => {
  formData.phone = phone;
  channel.value = channelCode;
  formData.channelCode = channelCode;
  formData.channelType =
    deviceType.value == "IOS" ? 1 : deviceType.value == "Android" ? 0 : 2;
  isShow.value = true;
  try {
    await refreshCode();
  } catch {
  } finally {
  }
};

const onClose = () => {
  isShow.value = false;
  formData.channelCode = "";
};

defineExpose({ open });
</script>

<style scoped>
.custom-dialog-header {
  position: relative;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-icon {
  position: absolute;
  right: 16px;
  top: -10px;
  font-size: 18px;
  cursor: pointer;
  z-index: 1;
}

.tip {
  text-align: right;
  color: #7e7d7d;
  font-size: 12px;
  margin-right: 12px;
}
.phone-icon-image {
  height: 100%;
  display: flex;
  align-items: center;
}
.code-img {
  display: flex;
  align-items: center;
}
</style>
